﻿using AJWPFAdmin.Core.Components.AJTable.ViewModels;
using AJWPFAdmin.Core.Crypto.AES;
using AJWPFAdmin.Core.Crypto.RSA;
using AJWPFAdmin.Core.Crypto.SMCrypto;
using AJWPFAdmin.Core.Enums;
using AJWPFAdmin.Core.ExtensionMethods;
using AJWPFAdmin.Core.GlobalEvents;
using AJWPFAdmin.Core.HardwareSDKS.Models;
using AJWPFAdmin.Core.Logger;
using AJWPFAdmin.Core.Models;
using AJWPFAdmin.Core.Models.EF.Tables;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Services.EF;
using AJWPFAdmin.Services.EF.TableExts;
using AJWPFAdmin.Services.Models;
using com.github.xiangyuecn.rsacsharp;
using Dapper;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Wordprocessing;
using Masuit.Tools.Reflection;
using Masuit.Tools.Security;
using MaterialDesignThemes.Wpf;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Utilities;
using Prism.Ioc;
using Quartz.Logging;
using Quartz.Util;
using Quartz.Xml.JobSchedulingData20;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Reflection.Emit;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Windows;
using System.Windows.Interop;
using Yitter.IdGenerator;
using static AJWPFAdmin.Services.Jobs.QinYouGoodsInfoProcessJob;

namespace AJWPFAdmin.Services.AppointAPI
{
    public class QinYouAppointAPI : AppointAPIBase
    {
        private APIConfig _apiConfig;
        private SqlConnectionStringBuilder _sqlConnBuilder;
        private DbContextOptionsBuilder<DbService> _dbContextOptionsBuilder;

        public QinYouAppointAPI(ApplicationType appType,
            SystemConfigDictionary cfg,
            IContainerProvider svcProvider) : base(appType, cfg, svcProvider)
        {
            _sqlConnBuilder = new SqlConnectionStringBuilder
            {
                //DataSource = apiConfig.DbServer,
                //UserID = "measure_user",
                //Password = "qydb123",
                TrustServerCertificate = true,
                MultipleActiveResultSets = true,
            };

        }

        public override Task ConvertToCustomConfig(bool isReal)
        {
            _apiConfig = CommonUtil.TryGetJSONObject<APIConfig>(Config.StringValue) ?? new APIConfig();
            _customAPIConfig = _apiConfig;
            AutoUploadDataVerification = _apiConfig.AutoUploadDataVerification;



            if (isReal)
            {
                _sqlConnBuilder.DataSource = _apiConfig.DbServer;
                _sqlConnBuilder.UserID = _apiConfig.DbUserId;
                _sqlConnBuilder.Password = _apiConfig.DbPassword;
                _sqlConnBuilder.InitialCatalog = _apiConfig.DbName;

                _dbContextOptionsBuilder = new DbContextOptionsBuilder<DbService>();
                _dbContextOptionsBuilder.UseSqlServer(_sqlConnBuilder.ConnectionString, bd =>
                {
                    bd.CommandTimeout(15);
                    bd.EnableRetryOnFailure(3);
                });

                //if (_appType == ApplicationType.岗亭端)
                //{

                //}
            }
            else
            {
                _ = GetSchemas();
            }

            return Task.CompletedTask;
        }

        protected override void OnAPILogsRaised(PassagewayDirection? direction,
            string logs)
        {
            base.OnAPILogsRaised(direction, logs);
        }

        public override async Task<ProcessResult> UploadShippingRecordAsync(ShippingRecordParams @params)
        {
            ////TODO: 本地调试模式,上线后注释
            //return new ProcessResult
            //{
            //    Success = true,
            //    Attach = new UploadShippingRecordResponse
            //    {
            //        GoodsNum = 1,
            //        RecordNum = 1
            //    }
            //};

            ProcessResult result;
            var response = new UploadShippingRecordResponse();

            result = new ProcessResult();
            result.SetSuccess();
            result.Attach = response;

            return result;
        }

        public async Task<ProcessResult> CustomUploadShippingRecordAsync(ShippingRecordParams @params, QinYouGoodsInfoModel goodsInfo)
        {
            var result = new ProcessResult();
            var record = @params.Record;
            try
            {
                using var mssqlDb = new DbService(_dbContextOptionsBuilder.Options);

                var conn = mssqlDb.Database.GetDbConnection();

                short vehicle_color_index = 0;
                switch (record.PlateColor)
                {
                    case CarPlateColor.蓝牌:
                        vehicle_color_index = 1;
                        break;
                    case CarPlateColor.黄牌:
                        vehicle_color_index = 2;
                        break;
                    case CarPlateColor.白牌:
                        vehicle_color_index = 3;
                        break;
                    case CarPlateColor.黑牌:
                        vehicle_color_index = 4;
                        break;
                    case CarPlateColor.新能源绿牌:
                        vehicle_color_index = 5;
                        break;
                    case CarPlateColor.其他:
                        
                    case CarPlateColor.新能源黄牌:
                        
                    case CarPlateColor.渐变绿牌:
                        vehicle_color_index = 6;
                        break;
                    default:
                        break;
                }

                var entity = new InAndOut_Date_Union_Entity
                {
                    number_plate = record.CarNo,
                    in_time = record.ShipStartDate.GetValueOrDefault(),
                    in_image = string.Empty,
                    in_gate_post_code = record.WatchhouseCode,
                    in_transport_volume = record.InGoodsVolume.ToString(),
                    in_transport_name = record.InGoodsName,
                    in_transport_time = goodsInfo.suttletime.GetValueOrDefault(),
                    out_time = record.ShipEndDate.GetValueOrDefault(),
                    out_image = string.Empty,
                    out_gate_post_code = record.OutWatchhouseCode,
                    out_transport_volume = record.OutGoodsVolume.ToString(),
                    out_transport_name = record.OutGoodsName,
                    out_transport_time = goodsInfo.suttletime.GetValueOrDefault(),
                    vehicle_color_index = vehicle_color_index,
                    in_transport_code = string.Empty,
                    out_transport_code = string.Empty,
                    in_transport_type = record.InGoodsType,
                    out_transport_type = record.OutGoodsType,
                    in_company = record.Sender,
                    out_company = record.Receiver,
                    vehicle_use_type = (short)(record.OutGoodsIsBulkCargo.GetValueOrDefault() ? 1 : 0),
                    sync_state = 1,
                    create_time = record.ShipStartDate.GetValueOrDefault(),
                    update_time = goodsInfo.suttletime.GetValueOrDefault()
                };

                var columns = entity.GetColumns();

                var count = await conn.ExecuteAsync($"insert into InAndOut_Date_Union ({string.Join(",", columns)}) values ({string.Join(",", columns.Select(p => $"@{p}"))})", entity);

                result.SetSuccess(count);
            }
            catch (Exception e)
            {
                result.SetError($"{record.CarNo} 插入台账数据表失败:{e.Message}");
            }

            return result;
        }

        public new void Dispose()
        {

        }

        public class InAndOut_Date_Union_Entity
        {
            /// <summary>
            /// 车牌号
            /// </summary>
            public string number_plate { get; set; }

            /// <summary>
            /// 进厂时间
            /// </summary>
            public DateTime in_time { get; set; }

            /// <summary>
            /// 进厂合成照片URL地址（顶部拍摄照片+进厂车辆照片）
            /// </summary>
            public string in_image { get; set; }

            /// <summary>
            /// 进厂门岗编号
            /// </summary>
            public string in_gate_post_code { get; set; }

            /// <summary>
            /// 进厂物料重量	必要 净重
            /// </summary>
            public string in_transport_volume { get; set; }

            /// <summary>
            /// 进厂物料名	必要
            /// </summary>
            public string in_transport_name { get; set; }

            /// <summary>
            /// 进厂物料计量完成时间	必要 二次称重时间
            /// </summary>
            public DateTime in_transport_time { get; set; }

            /// <summary>
            /// 出厂时间	必要
            /// </summary>
            public DateTime out_time { get; set; }

            /// <summary>
            /// 出厂合成照片URL地址（顶部拍摄照片+出厂车辆照片）	必要 
            /// </summary>
            public string out_image { get; set; }

            /// <summary>
            /// 出厂门岗编号	必要
            /// </summary>
            public string out_gate_post_code { get; set; }

            /// <summary>
            /// 出厂物料重量	必要 净重
            /// </summary>
            public string out_transport_volume { get; set; }

            /// <summary>
            /// 出厂物料名	必要 
            /// </summary>
            public string out_transport_name { get; set; }

            /// <summary>
            /// 出厂物料计量完成时间	必要 二次计量时间
            /// </summary>
            public DateTime out_transport_time { get; set; }

            /// <summary>
            /// 车牌颜色索引0 未知；1 蓝牌 ； 2 黄牌；3 白牌；4 黑牌；5 绿牌； 6 黄绿牌'	必要
            /// </summary>
            public short vehicle_color_index { get; set; }

            /// <summary>
            /// 进场物料单编码	必要
            /// </summary>
            public string in_transport_code { get; set; }

            /// <summary>
            /// 出场物料单编码	必要
            /// </summary>
            public string out_transport_code { get; set; }

            /// <summary>
            /// 进场物料类型	必要 物料分类
            /// </summary>
            public string in_transport_type { get; set; }

            /// <summary>
            /// 出场物料类型	必要  物料分类
            /// </summary>
            public string out_transport_type { get; set; }

            /// <summary>
            /// 发货方	非必要
            /// </summary>
            public string in_company { get; set; }

            /// <summary>
            /// 收货方	非必要
            /// </summary>
            public string out_company { get; set; }

            /// <summary>
            /// 车辆使用类型(0:未知;1:大宗商品运输;2:非大宗商品运输)	必要 物流
            /// </summary>
            public short vehicle_use_type { get; set; }

            /// <summary>
            /// 0-未同步 1-同步 2-更新后需要同步	必要(推送时此字段设置成0，更新时此字段设置成 2)
            /// </summary>
            public short sync_state { get; set; }

            /// <summary>
            /// 创建时间	必要(设置成进厂时间)
            /// </summary>
            public DateTime create_time { get; set; }

            /// <summary>
            /// 修改时间	非必要(二次称重及出厂时设置此字段)
            /// </summary>
            public DateTime update_time { get; set; }

            public string[] GetColumns()
            {
                return GetType().GetRuntimeProperties().Select(p => p.Name).ToArray();
            }
        }

        public class APIConfig : APIConfigBase
        {
            private string _dbServer;
            /// <summary>
            /// 数据库地址
            /// </summary>
            [DynamicFormItemDefine("数据库地址")]
            public string DbServer
            {
                get => _dbServer;
                set => _dbServer = value;
            }

            private string _dbUserId;
            /// <summary>
            /// 数据库地址
            /// </summary>
            [DynamicFormItemDefine("数据库账户")]
            public string DbUserId
            {
                get => _dbUserId;
                set => _dbUserId = value;
            }

            private string _dbPassword;
            /// <summary>
            /// 数据库地址
            /// </summary>
            [DynamicFormItemDefine("数据库密码")]
            public string DbPassword
            {
                get => _dbPassword;
                set => _dbPassword = value;
            }

            private string _dbName;
            /// <summary>
            /// 数据库地址
            /// </summary>
            [DynamicFormItemDefine("数据库名称")]
            public string DbName
            {
                get => _dbName;
                set => _dbName = value;
            }
        }
    }
}
